import io.github.bonigarcia.wdm.WebDriverManager;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.edge.EdgeOptions;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.Duration;

/**
 * @projectName: The-examination-questionnaire-pass-test
 * @package: PACKAGE_NAME
 * @className: Util
 * @author: Tongxinxin
 * @description: 通用方法
 * @date: 2025/9/22 0:26
 * @version: 1.0
 */
public class Util {
    public static WebDriver driver;
    //创建对象
    public static WebDriver createDriver(){
        if(driver == null){
            //设置本地Edge驱动路径
            System.setProperty("webdriver.edge.driver","D:\\Java\\Maven\\.m2\\edgedriver_win64\\msedgedriver.exe");
            EdgeOptions options = new EdgeOptions();
            //添加配置：允许访问所有连接
            options.addArguments("--remote-allow-origins=*");
            //创建驱动对象
            driver=new EdgeDriver(options);
            //设隐式等待
            driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(3));

        }
        return driver;
    }
    public Util(String url) {
        //调用driver对象
        driver = createDriver();
        //访问url
        driver.get(url);
    }

    //实现屏幕截图
    public void getScreenShot(String str) throws IOException {
        //命名格式为./src/test/image/2025/9/20/test01-11-11-11.png
        SimpleDateFormat sim1= new SimpleDateFormat("YYYY-MM-dd");
        SimpleDateFormat sim2= new SimpleDateFormat("HH-mm-ss");
        //通过获取当前的时间戳保存文件夹和文件名称
        String dirTime = sim1.format(System.currentTimeMillis());
        String fileTime = sim2.format(System.currentTimeMillis());

        String filename="./src/test/image/" +dirTime+"/"+str+"-"+fileTime+".png";
        File srcFile=((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);

        //将scrFile放在指定位置
        FileUtils.copyFile(srcFile,new File(filename));
    }

    //销毁driver对象，关闭浏览器
    public static void quit(){
        if(driver!=null){
            driver.quit();
        }
    }
}
